import { request, USE_MOCK } from './request'

export interface UploadArticleParams {
  title: string
  content: string
}
// src/api/upload.ts
export interface UploadFileResult {
  code: number
  message?: string
  url?: string // 保留兼容
  data?: { url: string } // 新增：真接口统一用 data 包裹
}
export interface UploadArticleResult {
  code: number
  message?: string
  articleId?: number
}

export const uploadArticle = async (params: UploadArticleParams): Promise<UploadArticleResult> => {
  if (USE_MOCK) {
    console.log('Mock 上传文章', params)
    return request(
      {},
      { code: 200, message: '本地测试成功', articleId: Math.floor(Math.random() * 1000) }
    )
  }
  return request({ url: '/article/upload', method: 'post', data: params })
}

export const uploadFile = async (file: File): Promise<{ url: string }> => {
  if (USE_MOCK) {
    console.log('Mock 上传文件', file.name)
    return { url: URL.createObjectURL(file) }
  }
  const formData = new FormData()
  formData.append('file', file)
  const res = await request<UploadFileResult>({
    url: '/file/upload',
    method: 'post',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' }
  })
  // 兼容两种返回：后端直接 url 或放在 data 里
  return { url: res.url ?? res.data?.url ?? '' }
}
